package com.example.picofteacherend.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.picofteacherend.auth.JwtUtil;
import com.example.picofteacherend.dto.RegisterDto;
import com.example.picofteacherend.entity.Role;
import com.example.picofteacherend.entity.User;
import com.example.picofteacherend.mapper.UserMapper;
import com.example.picofteacherend.service.UserService;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

/**
 * @author: zhk
 * @description:
 * @date: 2023/3/19 20:03
 * @version: 1.0
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    UserMapper userMapper;
    /**
     * 用户登录
     *
     * @param no       学号
     * @param password 密码
     * @return User
     */
    @Override
    public String login(String no, String password) {
        String tokenPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        User existUser = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getNo, no));
        if (existUser == null){
            return "用户不存在";
        }
        if(!existUser.getPassword().equals(tokenPassword)){
            return "密码不正确";
        }
        String token = JwtUtil.sign(no, tokenPassword);
        return token;
    }

    /**
     * 用户注册
     *
     * @param registerDto 注册对象
     * @return boolean
     */
    @Override
    public boolean register(RegisterDto registerDto) {
        // 判断学号是否已存在
        User existUser = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getNo, registerDto.getNo()));
        if (existUser != null) {
            log.error("该学号已被注册");
            return false;
        }
        // 对密码进行 MD5 加密
        registerDto.setPassword(DigestUtils.md5DigestAsHex(registerDto.getPassword().getBytes()));
        User user = new User();
        user.setName(registerDto.getName());
        user.setNo(registerDto.getNo());
        user.setPassword(registerDto.getPassword());
        user.setRole(Role.STUDENT.toString());
        user.setDepartment(registerDto.getDepartment());
        return userMapper.insert(user) == 1;
    }

    @Override
    public User findByUserNo(String no) {
        return userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getNo, no));
    }

}
